package org.jeecg.glr.iframe.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.glr.domain.glr.GlrGateWayControlLight;
import org.jeecg.glr.domain.glr.GlrGateWayLightGateWayDomain;
import org.jeecg.glr.domain.led.DataDomain;
import org.jeecg.glr.entity.GlrGateway;
import org.jeecg.glr.entity.GlrVideo;
import org.jeecg.glr.iframe.service.IGlrIframeVideoMonitoringService;
import org.jeecg.glr.iframe.util.AjaxJson;
import org.jeecg.glr.service.IGateWayCommon;
import org.jeecg.glr.service.IGlrGatewayService;
import org.jeecg.glr.service.IGlrVideoService;
import org.jeecg.glr.service.IGlrVideoYsService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.ResponseMessage;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.jeecg.common.constant.CommonConstant.St_Access_Token;

/**
 *iframe使用
 * GIS功能
 */
@Slf4j
@Controller
@RequestMapping("/iframeGlr/lightGis")
public class GlrIframeLightGis extends JeecgController<GlrVideo, IGlrVideoService> {

    @Autowired
    private IGlrIframeVideoMonitoringService glrIframeVideoMonitoringService;

    @Autowired
    private IGlrVideoYsService glrVideoYsService;

    @Value("${glr.path.vue_url}")
    private String vue_url;

    @Resource
    IGateWayCommon gateWayCommon;

    @Value("${glr.url.led_status}")
    private String led_status;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IGlrGatewayService glrGatewayService;

    /**
     * 人脸列表
     * @param modelAndView
     * @return
     */
    @RequestMapping("/index")
    public String list(Model model, HttpServletRequest request) throws Exception {
        try{
            LoginUser loginUser=glrIframeVideoMonitoringService.updateUserInfo(request);
            if (loginUser==null){
                return "redirect:"+vue_url;
            }
        }catch (Exception ex){
            return "redirect:"+vue_url;
        }
        model.addAttribute("AccessToken",request.getParameter(St_Access_Token));
        return "/glrTemplates/LightGis/index";
    }

    @RequestMapping("/styleJson")
    @ResponseBody
    public Object styleJson(Model model, HttpServletRequest request) throws Exception {
        try{
            LoginUser loginUser=glrIframeVideoMonitoringService.updateUserInfo(request);
            if (loginUser==null){
                return "redirect:"+vue_url;
            }
        }catch (Exception ex){
            return "redirect:"+vue_url;
        }

        //F:\hp\yshopmall2020\lbyrun\glrics1\jeecg-boot\jeecg-boot-module-system\src\main\resources\templates\glrTemplates\LightGis
        File file = ResourceUtils.getFile("classpath:templates/glrTemplates/LightGis/styleJson.json");
        String stJson="";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                //System.out.println("line " + line + ": " + tempString);
                stJson=stJson+tempString;
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        AjaxJson j = new AjaxJson();
        j.setObj(stJson);

        return j;
    }


    /**
     * 取当前传感器最新的数据
     * @param model
     * @param code
     * @return
     */
    public static LoginUser loginUserTemp=null;
    @RequestMapping("/getGateWayList")
    @ResponseBody
    public AjaxJson getGateWayList(HttpServletRequest request,Model model) throws Exception {
        String stSql="select current_work_status as currentWorkStatus ,gate_way_code as gatewayCode,gateway_name as gatewayName,longitude,latitude,IFNULL(control_number,0) as lightNum,id\n" +
                "from glr_gateway";

        LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

        loginUserTemp=loginUser;

        if(loginUser!=null){
            if(!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_0)&&!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                stSql=stSql+" where sys_company_code='"+ loginUser.getSysCompanyCode()+"'";
            }
        }

        List<Map<String, Object>> dataList=glrVideoYsService.doGetListForJdbc(stSql);
        AjaxJson j = new AjaxJson();
        if (dataList.size()>0){
            for(Map<String, Object> map:dataList){
                if (StringUtil.isNotEmpty(map.get("currentWorkStatus"))){
                    String currentWorkStatus =map.get("currentWorkStatus").toString();
                    if(StringUtil.isNotEmpty(currentWorkStatus)&&GLRConstant.YN_Y.equals(currentWorkStatus)){
                        map.put("currentWorkStatus",GLRConstant.YN_Y);
                    }else{
                        map.put("currentWorkStatus",GLRConstant.YN_N);
                    }
                }else{
                    map.put("currentWorkStatus",GLRConstant.YN_N);
                }
            }
            j.setObj(dataList);
        }
        return j;
    }


    /**
     * 取当前传感器最新的数据
     * @param model
     * @param code
     * @return
     */
    @RequestMapping("/lightByGateWayCode")
    @ResponseBody
    public AjaxJson lightByGateWayCode(HttpServletRequest request,Model model, String gateWayCode) throws Exception {
        LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

        String stSql="select a.code as ligCode, " +
                "light_type_code as ligspeCode,\n" +
                "b.name as ligspeName,\n" +
                "gate_way_code as gateWayCode," +
                "IFNULL(current_vol,0) as currentVol,\n" +
                "IFNULL(current_cur,0) as currentCur,\n" +
                "current_status as currentStatus,\n" +
                "IFNULL(current_brightness,0) as currentBrightness,a.id as id,\n" +
                "latitude as latitude,\n" +
                "longitude as longitude \n" +
                "from glr_light a\n" +
                "left join glr_light_type b on a.light_type_code=b.code\n" +
                "where a.gate_way_code='"+gateWayCode+"'";
        if(loginUser!=null){
            if(!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_0)&&!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                stSql=stSql+" and a.sys_company_code='"+ loginUser.getSysCompanyCode()+"'";
            }
        }

        List<Map<String, Object>> dataList=glrVideoYsService.doGetListForJdbc(stSql );
        AjaxJson j = new AjaxJson();
        if (dataList.size()>0){
            for(Map<String, Object> aa:dataList){
                Object currentStatus =aa.get("currentStatus");
                if(StringUtil.isNotEmpty(currentStatus)&&GLRConstant.YN_Y.equals(currentStatus)){
                    aa.put("currentStatus",GLRConstant.YN_Y);
                }else if(StringUtil.isNotEmpty(currentStatus)&&GLRConstant.YN_K.equals(currentStatus)){
                    aa.put("currentStatus",GLRConstant.YN_K);
                }else{
                    aa.put("currentStatus",GLRConstant.YN_N);
                }
            }
            j.setObj(dataList);
        }
        return j;

    }



    @RequestMapping("/gatawayPatternList")
    public String gatawayPatternList(Model model,HttpServletRequest request){
        //request.setAttribute("gatewayCode", request.getParameter("gatewayCode"));
        String gatewayType = request.getParameter("gatewayType");
        if ("selectWin".equals(gatewayType)){
            //return new ModelAndView("/glrTemplates/LightGis/gatawayPatternList");
        }
        try{
            LoginUser loginUser=glrIframeVideoMonitoringService.updateUserInfo(request);
            if (loginUser==null){
                return "redirect:"+vue_url;
            }
        }catch (Exception ex){
            return "redirect:"+vue_url;
        }
        model.addAttribute("AccessToken",request.getParameter(St_Access_Token));
        return "/glrTemplates/LightGis/gatawayPatternList";
    }

    @RequestMapping("/gatawayPatternDatagrid")
    @ResponseBody
    public Result<?> gatawayPatternDatagrid(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = true) Map<String, Object> map){
        try{
            LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

            Object gatewayCode = map.get("gatewayCode");
            Object lightCode = map.get("lightCode");
            Object lightId = map.get("lightId");
            List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();

            gatewayCode="333";

            String stSql="select DISTINCT a.*\n" +
                    "from glr_pattern a\n" +
                    "left join glr_pattern_gateway b on b.pattern_id=a.id\n";
            if (StringUtil.isNotEmpty(gatewayCode)){
                stSql=stSql+"where b.gate_way_code='"+gatewayCode+"'";
            }else {
                stSql=stSql+"left join glr_light c on c.gate_way_code=b.gate_way_code\n" +
                        "where c.id='"+lightId+"' and c.code='"+lightCode+"'\n";
            }
            if(loginUser!=null){
                if(!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_0)&&!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                    stSql=stSql+" and a.sys_company_code='"+ loginUser.getSysCompanyCode()+"'";
                }
            }

            List<Map<String, Object>> dataList=glrVideoYsService.doGetListForJdbc(stSql);
            return Result.ok(dataList);
        }catch (Exception e){
        }
        return  Result.error("没有找到值");
    }

    /**
     * 向网关服务发送请求
     * @param request
     * @param response
     * @param map
     * @return
     */
    @RequestMapping("/gatawaySetBrightness")
    @ResponseBody
    public Result<?> gatawaySetBrightness(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = true) Map<String, Object> map){
        try{
            LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

            Object gatewayCode = map.get("gatewayCode");
            Object brightValue = map.get("brightValue");

            Object lightId = map.get("lightId");
            Object lightCode = map.get("lightCode");

            if (StringUtil.isNotEmpty(lightId)&&StringUtil.isNotEmpty(lightCode)){
                //灯发送命令
                GlrGateWayControlLight lg = new GlrGateWayControlLight();
                lg.setGateWayCode(gatewayCode.toString());
                lg.setBrightValue(Integer.parseInt(brightValue.toString()));
                lg.setLightCode(lightCode.toString());
                lg.setType(GLRConstant.GLR_GATE_WAY_CONTROL_LIGHT_TYPE_01);
                gateWayCommon.ledOpenOrClose(lg);
            }else{
                //网关发送命令
                GlrGateWayControlLight lg = new GlrGateWayControlLight();
                lg.setGateWayCode(gatewayCode.toString());
                lg.setBrightValue(Integer.parseInt(brightValue.toString()));
                lg.setType(GLRConstant.GLR_GATE_WAY_CONTROL_LIGHT_TYPE_03);
                gateWayCommon.ledOpenOrClose(lg);
            }
            return Result.ok("已发送成功!");
        }catch (Exception e){

        }
        return  Result.error("没有找到值");
    }

    /**
     * 取网关服务的数据
     * @param request
     * @param response
     * @param map
     * @return
     */
    @RequestMapping("/getMsg")
    @ResponseBody
    public Result<?> getMsg(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = true) Map<String, Object> map){
        try{
            LoginUser loginUser= glrIframeVideoMonitoringService.updateUserInfo(request);

            Object gatewayCode = map.get("gatewayCode");
            Object command = map.get("command");

            List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();


            return Result.ok("111");
        }catch (Exception e){
        }
        return  Result.error("没有找到值");
    }





}
